﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AES小工具
{
    public partial class FrmIpCalc : Form
    {
        public FrmIpCalc()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 计算参考连接 : https://www.cnblogs.com/lidabo/p/5308334.html
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnBroadcastIp_Click(object sender, EventArgs e)
        {
            string computerIpStr = tbComputerIp.Text.Trim();
            string maskIpStr = tbMask.Text.Trim();

            string[] computerIpStrs = computerIpStr.Split('.');
            if (computerIpStrs.Length != 4) {
                MessageBox.Show("电脑IP输入不正确!");
                return;
            }

            byte[] computerIpBytes = new byte[computerIpStrs.Length];
            for (int i = 0;i<computerIpBytes.Length;i++) {
                computerIpBytes[i] = Convert.ToByte(computerIpStrs[i]);
            }

            string[] maskIpStrs = maskIpStr.Split('.');
            if (maskIpStrs.Length != 4) {
                MessageBox.Show("掩码输入不正确!");
                return;
            }

            byte[] maskIpBytes = new byte[maskIpStrs.Length];
            for (int i = 0; i < maskIpBytes.Length; i++) {
                maskIpBytes[i] = Convert.ToByte(maskIpStrs[i]);
            }

            byte[] broadcastDomainIpBytes = new byte[4];
            byte[] broadcastIpBytes = new byte[4];

            //求广播域
            for (int i = 0; i < 4; i++) {
                broadcastDomainIpBytes[i] = (byte)(computerIpBytes[i] & maskIpBytes[i]);
            }

            //求广播IP
            for (int i = 0; i < 4; i++) {

                byte b = (byte)( ~ maskIpBytes[i]);
                broadcastIpBytes[i] = (byte)(computerIpBytes[i] | b);
            }

            tbBroadcastDomain.Text =  broadcastDomainIpBytes[0].ToString() + "."
                                    + broadcastDomainIpBytes[1].ToString() + "."
                                    + broadcastDomainIpBytes[2].ToString() + "."
                                    + broadcastDomainIpBytes[3].ToString();
            tbBroadcastIp.Text = broadcastIpBytes[0].ToString() + "."
                + broadcastIpBytes[1].ToString() + "."
                + broadcastIpBytes[2].ToString() + "."
                + broadcastIpBytes[3].ToString();
        }
    }
}
